<template>
  <div>
    <!-- 头部面包屑 -->
    <el-breadcrumb separator-class="el-icon-arrow-right">
      <el-breadcrumb-item :to="{ path: '/home' }">首页</el-breadcrumb-item>
      <el-breadcrumb-item>权限管理</el-breadcrumb-item>
      <el-breadcrumb-item>角色列表</el-breadcrumb-item>
    </el-breadcrumb>
    <el-card>
      <el-button type="primary">添加角色</el-button>
      <el-table :data="roleList" border stripe>
        <el-table-column type="expand">
          <template slot-scope="scope">
            <!-- 使用栅栏系统渲染权限 -->
            <el-row
              v-for="(yiji,i1) in scope.row.children"
              :key="i1"
              :class="['bdbottom', i1==0?'bdtop':'', 'vcenter']"
            >
              <!-- 渲染一级权限 -->
              <el-col :span="5">
                <el-tag type closable @close="removeRightById(scope.row,yiji.id)">{{yiji.authName}}</el-tag>
                <i class="el-icon-caret-right"></i>
              </el-col>
              <!-- 渲染二级和三级权限 -->
              <el-col :span="19">
                <el-row
                  v-for="(erji,i2) in yiji.children"
                  :key="i2"
                  :class="['vcenter', i2==0?'':'bdtop']"
                >
                  <el-col :span="6">
                    <el-tag
                      type="success"
                      closable
                      @close="removeRightById(scope.row,erji.id)"
                    >{{erji.authName}}</el-tag>
                    <i class="el-icon-caret-right"></i>
                  </el-col>
                  <el-col :span="18">
                    <el-tag
                      type="warning"
                      closable
                      v-for="(sanji,i3) in erji.children"
                      :key="i3"
                      @close="removeRightById(scope.row,sanji.id)"
                    >{{sanji.authName}}</el-tag>
                  </el-col>
                </el-row>
              </el-col>
            </el-row>
            <!-- <pre>
              {{scope.row}}
            </pre>-->
          </template>
        </el-table-column>
        <el-table-column label="#" type="index" width="40">
          <template slot-scope="scope">{{scope.$index+1}}</template>
        </el-table-column>
        <el-table-column label="角色名称" prop="roleName"></el-table-column>
        <el-table-column label="角色描述" prop="roleDesc"></el-table-column>
        <el-table-column label="操作">
          <template slot-scope="scope">
            <el-tooltip effect="dark" content="编辑" placement="top" :enterable="false">
              <el-button size="mini" type="primary" icon="el-icon-edit">编辑</el-button>
            </el-tooltip>
            <el-tooltip effect="dark" content="删除" placement="top" :enterable="false">
              <el-button size="mini" type="danger" icon="el-icon-delete">删除</el-button>
            </el-tooltip>
            <el-tooltip effect="dark" content="分配权限" placement="top" :enterable="false">
              <el-button
                size="mini"
                type="warning"
                icon="el-icon-setting"
                @click="showSetRightDialog(scope.row.children,scope.row.id)"
              >分配权限</el-button>
            </el-tooltip>
          </template>
        </el-table-column>
      </el-table>
    </el-card>
    <!-- 分配权限的对话框 -->
    <el-dialog title="提示" :visible.sync="rightsdialogVisible" width="50%">
      <el-tree
        :data="rightsList"
        show-checkbox
        node-key="id"
        :props="defaultProps"
        :default-expand-all="true"
        :default-checked-keys="defKeys"
        ref="treeRef"
      ></el-tree>
      <span slot="footer" class="dialog-footer">
        <el-button @click="rightsdialogVisible = false">取 消</el-button>
        <el-button type="primary" @click="allotRights">确 定</el-button>
      </span>
    </el-dialog>
  </div>
</template>

<script>
export default {
  data() {
    return {
      roleList: [],
      // 分配权限对话框显示
      rightsdialogVisible: false,
      rightsList: [],
      defaultProps: {
        children: "children",
        label: "authName"
      },
      // 默认选中的节点id值
      defKeys: [],
      roleId:''
    };
  },
  created() {
    this.getRoleList();
  },
  methods: {
    // 点击为角色分配权限
    async allotRights(){
      const keys = [
        ...this.$refs.treeRef.getCheckedKeys(),
        ...this.$refs.treeRef.getHalfCheckedKeys()
      ]
      const idStr = keys.join(',')
      const {data: res} = await this.$http.post(`roles/${this.roleId}/rights`,{rids: idStr})
      if(res.meta.status!==200) return this.$message.error('更新失败')
      this.rightsdialogVisible = false
      this.getRoleList()
      return this.$message.success('更新成功！')

    },
    // 递归函数遍历节点将最后一个节点的id值插入defKeys数组中
    leafRrightsNode(node) {
      node.forEach(element => {
        if (!element.children) {
          this.defKeys.push(element.id);
        } else {
          this.leafRrightsNode(element.children);
        }
      });
    },
    async showSetRightDialog(node,roleId) {
      this.defKeys = [];
      // 获取所有权限数据
      const { data: res } = await this.$http.get("rights/tree");
      if (res.meta.status !== 200)
        return this.$message.error("获取权限列表失败");
      this.rightsList = res.data;
      this.leafRrightsNode(node);
      this.roleId = roleId
      this.rightsdialogVisible = true;
    },
    async getRoleList() {
      const { data: res } = await this.$http.get("roles");
      this.roleList = res.data;
      console.log(this.roleList);
    },
    async removeRightById(role, Id) {
      const resConfirm = await this.$msbox
        .confirm("确认删除该权限吗?", "警告", {
          confirmButtonText: "确定",
          cancelButtonText: "取消",
          type: "warning"
        })
        .catch(err => err);
      if (resConfirm === "cancel") return this.$message.info("已取消删除");
      const { data: res } = await this.$http.delete(
        `roles/${role.id}/rights/${Id}`
      );
      if (res.meta.status !== 200) return this.$message.error("删除权限失败！");
      this.$message.success("删除成功");
      role.children = res.data;
    }
  }
};
</script>

<style lang='less' scoped>
.el-tag {
  margin: 7px;
}

.bdtop {
  border-top: 1px solid #eee;
}

.bdbottom {
  border-bottom: 1px solid #eee;
}

.vcenter {
  display: flex;
  align-items: center;
}
</style>
